package com.thinvent.remotepassword.util;

import cn.hutool.core.bean.BeanUtil;
import com.thinvent.remotepassword.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final long TOKEN_VALIDITY = 86400000;
    private static final String SALT_KEY = "caiwu";
    /**
     * 生成token
     *
     * @return
     */
    public static String getToken(User user) {
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(user);
        Date validity = new Date((new Date()).getTime()+ TOKEN_VALIDITY);
        String caiwu = Jwts.builder()
                .setClaims(stringObjectMap)
                .signWith(SignatureAlgorithm.HS512, SALT_KEY)
                .setExpiration(validity)
                .compact();
        return caiwu;
    }

    public static User checkToken(String token) {
        if(validateToken(token)){
            Claims body = Jwts.parser()
                    .setSigningKey(SALT_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            String id = body.get("id", String.class);
            String username = body.get("username", String.class);
            String userpwd = body.get("userpwd", String.class);
            Integer status = body.get("status", Integer.class);


            User user = new User() {{
                setStatus(status);
                setId(id);
                setUsername(username);
                setUserpwd(userpwd);
            }};
            return user;
        }
        return null;
    }
    private static boolean validateToken(String authToken){
        try{
            Jwts.parser().setSigningKey(SALT_KEY)
                    .parseClaimsJws(authToken);
            return true;
        }catch(Exception e){
            return false;
        }
    }

}
